package com.aj.checkserver.timing;

import com.aj.checkserver.domain.ApiResult;
import com.aj.checkserver.domain.Check;
import com.aj.checkserver.domain.HostNmaeVo;
import com.aj.checkserver.util.sms.SmsCodeUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

import static com.aj.checkserver.util.HostUtil.hostNmaeVos;

@Component
public class CheckServer {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private Check check;


    Date date = new Date();
    Gson gson = new Gson();

    @Scheduled(cron = "* */10 * * * *")
    public void check() {
        ApiResult apiResult;
        try {
            apiResult = restTemplate.getForObject(check.getUrl(), ApiResult.class);
            System.out.println(apiResult.getData().toString());
            String hostName = apiResult.getData().toString().trim();
            date = new Date();
            if (gson.toJson(hostNmaeVos).indexOf(hostName) < 0) {
                HostNmaeVo hostNmaeVo = new HostNmaeVo();
                hostNmaeVo.setHostname(hostName);
                hostNmaeVo.setDate(date);
                hostNmaeVo.setNum(1);
                hostNmaeVos.add(hostNmaeVo);
            } else {
                for (HostNmaeVo hostNmaeVo : hostNmaeVos) {
                    if (hostNmaeVo.getHostname().equals(hostName)) {
                        hostNmaeVo.setNum(hostNmaeVo.getNum() + 1);
                        hostNmaeVo.setDate(date);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("=========>>无法访问");
            hostNmaeVos.sort((HostNmaeVo h1, HostNmaeVo h2) -> h2.getDate().compareTo(h1.getDate()));
            for (String p :  check.getPhones()) {
                SendSmsResponse sendSmsResponse = SmsCodeUtil.sendNotice(p,"aj");
                System.out.println(sendSmsResponse.getMessage());
            }


        }


    }

}
